<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of PlayerNationalTeam
 *
 * @author Laszlo.Pokoradi
 */
class PlayerNationalTeam {
  const SENIOR_XPATH = "./@senior";
  const YOUTH_XPATH = "./@youth";

  private $senior;
  private $youth;
  private $db;

  public function __construct($database) {
    $this->db = $database;

    $this->senior = false;
    $this->youth = false;
  }

  public function loadFromNode(DOMElement $docNode) {
    $doc = $docNode->ownerDocument;

    $xPath = new DOMXPath($doc);

    $qResult = $xPath->query(PlayerNationalTeam::SENIOR_XPATH,$docNode);
    $this->senior = $qResult->item(0)->nodeValue;

    $qResult = $xPath->query(PlayerNationalTeam::YOUTH_XPATH,$docNode);
    $this->youth = $qResult->item(0)->nodeValue;
  }

  public function insertNewToDB($playerId) {
    $this->db->set('playerId',$playerId);
    $this->db->set('senior',$this->senior);
    $this->db->set('youth',$this->youth);

    $query = $this->db->insert('playernationalteam');

    if (!$query) {
      log_message('error', 'Error during playernationalteam inserttion!');
      return false;
    }
    return $this->db->insert_id();
  }

  public function amendOldInDB($id) {
    $this->db->where('id',$id);
    $query = $this->db->get('playernationalteam');

    if (!$query) {
      log_message('error','Error during playernationalteam amendment!');
    } else {
      $tRow = $query->row();
      $oldId = $tRow->id;
      $playerId = $tRow->playerId;

      if ($tRow->senior!=$this->senior
          || $tRow->youth!=$this->youth) {
        $newId = $this->insertNewToDB($playerId);

        $this->db->set('playerId', $playerId);
        $this->db->set('table','playernationalteam');
        $this->db->set('oldId',$oldId);
        $this->db->set('newId',$newId);
        $this->db->set('insertTime',date('Y-m-d H:i:s'));
        $query = $this->db->insert('playernationalteam');

        if (!$query) {
          log_message('error','Playernationalteam amend was unsuccesful!');
        } else {
          return $newId;
        }
      }
    }
    return $oldId;
  }

  public function loadFromDB($nationalTeamId) {
    $this->db->where('id',$nationalTeamId);
    $query = $this->db->get('playernationalteam');

    if (!$query || $query->num_rows()==0) {
      log_message('error', 'PlayerNationalTeam ('.$nationalTeamId.') not found in the database!');
    } else {
      $result = $query->row();

      $this->senior = $result->senior;
      $this->youth = $result->youth;
    }
  }
}
?>
